package com.example.badminton.config;

import com.example.badminton.common.AnonymousAccess;
import com.example.badminton.entity.User;
import com.example.badminton.service.UserService;
import com.example.badminton.utils.JwtUtils;
import com.example.badminton.utils.UserContext;
import com.example.badminton.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 只拦截Controller方法
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();

            // 检查是否有@AnonymousAccess注解
            if (method.isAnnotationPresent(AnonymousAccess.class) ||
                handlerMethod.getBeanType().isAnnotationPresent(AnonymousAccess.class)) {
                return true;
            }

            // 获取token
            String token = request.getHeader("Authorization");
            if (token == null || token.isEmpty()) {
                return unauthorized(response, "未登录，请先登录");
            }

            // 校验token
            Long userId = JwtUtils.getUserIdFromToken(token);
            if (userId == null) {
                return unauthorized(response, "登录已失效，请重新登录");
            }

            User user = userService.getById(userId);
            if (user == null) {
                return unauthorized(response, "用户不存在或已被禁用");
            }

            // 注入用户信息到ThreadLocal
            UserContext.setUser(user);
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清理ThreadLocal，防止内存泄漏
        UserContext.clear();
    }

    private boolean unauthorized(HttpServletResponse response, String message) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter out = response.getWriter();
        out.write(Result.error(401, message).toJson());
        out.flush();
        out.close();
        return false;
    }
} 